﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using TM.QWeibo.Client;
using Microsoft.Phone.Shell;

namespace TM.QWeibo.Client
{
    public partial class Profile : PhoneApplicationPage
    {
        #region 私有变量

        string _accountName { get; set; }

        private SDK.Objects.UserInfo _user;

        /// <summary>
        /// 是否是我自己
        /// </summary>
        bool isMyself {
            get {
                return string.Compare(AppSetting.AccountName,_accountName)==0;
            }
        }

        #endregion

        public Profile()
        {
            InitializeComponent();
            profileTweetList.Selected = SelectTweet;
            idolList.Selected = SelectUser;
            fansList.Selected = SelectUser;
            fansList.GotLastest = ClearFansCount;
            favListTimeline.Selected = SelectTweet;
            profileTweetList.MenuItemClick = MenuItemClick;
            profileInfo.BlockClicked = BlockClicked;
            this.ApplicationBar.BackgroundColor = (Color)App.Current.Resources["ApplicationBarBackgroundColor"];
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (NavigationContext.QueryString.ContainsKey(AppSetting.UserNameParameterKey))
            {
                var name = NavigationContext.QueryString[AppSetting.UserNameParameterKey];
                if (!string.IsNullOrWhiteSpace(name))
                {
                    _accountName = name;
                    progressBar.IsIndeterminate = true;
                    GetUserInfo();
                }
            }
        }

        /// <summary>
        ///  请求用户数据
        /// </summary>
        private void GetUserInfo(){
            if (isMyself)
            {
                TM.QWeibo.Dal.User.Instance.MyInfo(GetUserInfoEnd);
            }
            else {
                TM.QWeibo.Dal.User.Instance.OtherUser(_accountName,GetUserInfoEnd);
            }
        }
        /// <summary>
        /// 请求用户资料回调
        /// </summary>
        /// <param name="userInfo"></param>
        private void GetUserInfoEnd(TM.QWeibo.SDK.Objects.UserInfo userInfo) {
            Dispatcher.BeginInvoke(() =>
            {
                _user = userInfo;
                UserInfo.BindInfo(userInfo);
                profileInfo.BindInfo(userInfo);
                tbIdolNum.Text =AppSetting.CheckBigNumber(userInfo.Idolnum);
                tbFansNum.Text = AppSetting.CheckBigNumber(userInfo.Fansnum);
                tbTweetNum.Text = AppSetting.CheckBigNumber(userInfo.Tweetnum);
                tbFavNum.Text = AppSetting.CheckBigNumber(userInfo.Favnum);
                progressBar.IsIndeterminate = false;
                InitButton(userInfo);
            });
        }


        /// <summary>
        /// 初始化页面的按钮
        /// </summary>
        /// <param name="user"></param>
        private void InitButton(SDK.Objects.UserInfo user) {
            Dispatcher.BeginInvoke(() => {

                var appbarbtns = this.ApplicationBar.Buttons;

                appbarbtns.Clear();

                var mitem = (ApplicationBarMenuItem) ApplicationBar.MenuItems[0];
                if(mitem!=null && isMyself)
                {
                    mitem.IsEnabled = true;
                }
                 if (!isMyself)
                {
                    var menuBlack = (ApplicationBarMenuItem)ApplicationBar.MenuItems[1];
                    menuBlack.IsEnabled = true;
                    menuBlack.Text = _user.IsMyBlack ? "取消拉黑" : "拉黑";

                    //收听按钮
                    var IdolBtn = new ApplicationBarIconButton
                    {
                        Text = user.IsMyidol ? "取消收听" : "收听",
                        IconUri = new Uri("/Resource/Icons/" + (user.IsMyidol ? "noidol" : "idol") + ".png", UriKind.Relative)
                    };
                    IdolBtn.Click += btnIdol_Click;
                    appbarbtns.Add(IdolBtn);

                    //收听我的人可以发私信
                    if (user.IsMyFans) {
                        var MessageBtn = new ApplicationBarIconButton
                        {
                            Text = "私信",
                            IconUri = new Uri("/Resource/Icons/message.png", UriKind.Relative)
                        };
                        MessageBtn.Click += btnMessage_Click;
                        appbarbtns.Add(MessageBtn);
                    }

                    //@某人
                    var MentioBtn = new ApplicationBarIconButton
                    {
                        Text = "@ta",
                        IconUri = new Uri("/Resource/Icons/mentions.png", UriKind.Relative)
                    };
                    MentioBtn.Click += btnMention_Click;
                    appbarbtns.Add(MentioBtn);
                }
                
                //返回首页
                var homeBtn= new ApplicationBarIconButton
                    {
                        Text = "首页",
                        IconUri = new Uri("/Resource/Icons/home.png", UriKind.Relative)
                    };
                    homeBtn.Click += btnHome_Click;
                    appbarbtns.Add(homeBtn);
            
            });

        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_user != null)
            {
                var index = pivotProfile.SelectedIndex;
                switch (index)
                {
                    case 1: profileTweetList.Init(_user.Name, BeforeLoading, AfterLoaded); break;
                    case 2: idolList.Init(_accountName, BeforeLoading, AfterLoaded); break;
                    case 3: fansList.Init(_accountName, BeforeLoading, AfterLoaded); break;
                    case 4: favListTimeline.Init(BeforeLoading,AfterLoaded); break;
                }
            }
        }

        /// <summary>
        /// 加载数据前显示loading状态
        /// </summary>
        private void BeforeLoading()
        {
            Dispatcher.BeginInvoke(() => progressBar.IsIndeterminate = true);
        }
        /// <summary>
        /// 加载数据后隐藏loading状态，显示相关信息
        /// </summary>
        private void AfterLoaded(object count)
        {
            Dispatcher.BeginInvoke(() =>
            {
                progressBar.IsIndeterminate = false;
            });
        }

        /// <summary>
        /// 选中微博，跳转到详细页
        /// </summary>
        /// <param name="t"></param>
        private void SelectTweet(SDK.Objects.Tweet t)
        {
            if (t != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(string.Format("/Tweet/Detail.xaml?{0}={1}", AppSetting.TweetIdParameterKey, t.Id), UriKind.Relative)));
            }
        }

        /// <summary>
        /// 选中用户，跳转到详细页
        /// </summary>
        /// <param name="t"></param>
        private void SelectUser(SDK.Objects.UserInfo u)
        {
            if (u != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(string.Format("/Profile.xaml?{0}={1}", AppSetting.UserNameParameterKey, u.Name), UriKind.Relative)));
            }
        }

        #region 按钮事件

        /// <summary>
        /// 收听按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnIdol_Click(object sender, EventArgs e)
        {
            if (_user.IsMyidol)
            {
                Dal.Friends.Instance.Delete(_user.Name, FriendActionEnd);
            }
            else {
                Dal.Friends.Instance.Add(_user.Name, FriendActionEnd);
            }
        }

        private void FriendActionEnd(bool rs) {
            if (rs) {
                _user.IsMyidolFlag = _user.IsMyidol ? 0 : 1;
                Dispatcher.BeginInvoke(() => {
                    var btn = (ApplicationBarIconButton)this.ApplicationBar.Buttons[0];
                    btn.IconUri = new Uri("/Resource/Icons/" + (_user.IsMyidol ? "noidol" : "idol") + ".png", UriKind.Relative);
                    btn.Text = _user.IsMyidol ? "取消" : "收听";
                    (new Helper.MessageBoxHelper()).Show((_user.IsMyidol ? "收听" + _user.NickName + "成功" : "已取消收听" + _user.NickName + "成功"), null, this.LayoutRoot);
                });
            }
        }

        /// <summary>
        /// 私信
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMessage_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}&{2}={3}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.PrivateMessage.GetHashCode(), AppSetting.AddTweetMetaParameterKey, _user.Name), UriKind.Relative));
        }
        /// <summary>
        /// 提及
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMention_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}&{2}={3}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.Mention.GetHashCode(),AppSetting.AddTweetMetaParameterKey,_user.Name), UriKind.Relative));
        }
        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHome_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        #endregion

        /// <summary>
        /// 清空新听众的计数
        /// </summary>
        public void ClearFansCount() {
            Dal.Status.Instance.Clear(SDK.Objects.UpdateCount.ECountType.Fans);
        }

        /// <summary>
        /// 控件弹出菜单服务
        /// </summary>
        /// <param name="t"></param>
        /// <param name="act"></param>
        private void MenuItemClick(SDK.Objects.Tweet t, Helper.EMenuItemAction act)
        {
            if (act == Helper.EMenuItemAction.Reply)
            {
                Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, t);
                NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.Reply.GetHashCode()), UriKind.Relative));
            }
            else if (act == Helper.EMenuItemAction.ReAdd)
            {
                Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, t);
                NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.ReAdd.GetHashCode()), UriKind.Relative));
            }
            else if (act == Helper.EMenuItemAction.Favorite)
            {

                Dal.Tweet.Instance.AddFavorite(t.Id, (rs) =>
                {
                    (new Helper.MessageBoxHelper()).Show("收藏" + (rs ? "成功" : "失败"), "提示", this.LayoutRoot);
                });

            }
            else if (act == Helper.EMenuItemAction.Comment)
            {
                Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, t);
                NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.Comment.GetHashCode()), UriKind.Relative));
            }
        }

        public void BlockClicked(int i)
        {
            if(i==0)
            {
                pivotProfile.SelectedIndex = 1;
            }
            else if(i==1)
            {
                pivotProfile.SelectedIndex = 2;
            }
            else if (i == 2)
            {
                pivotProfile.SelectedIndex = 3;
            }
            else if (i == 3)
            {
                pivotProfile.SelectedIndex = 4;
            }
        }

        private void downloadIdols_Click(object sender, EventArgs e)
        {
            Dal.Friends.Instance.DownloadIdolList(() => Dispatcher.BeginInvoke(() =>
            {
                progressBar.IsIndeterminate = true;
            }),
             ()=> Dispatcher.BeginInvoke(() =>
                                            {
                                                progressBar.IsIndeterminate = false;
                                                (new Helper.MessageBoxHelper()).Show("下载完成！", "", this.LayoutRoot);
                                            }));
        }

        private void addBlackList_Click(object sender, EventArgs e)
        {
            if(_user.IsMyBlack)
            {
                Dal.User.Instance.DeleteBlackList(_user.Name,(b)=>
                {
                    _user._IsMyBlack = b ? 0 : 1;
                    Dispatcher.BeginInvoke(() =>
                                               {
                                                   var menuBlack = (ApplicationBarMenuItem)ApplicationBar.MenuItems[1];
                                                   menuBlack.Text = _user.IsMyBlack ? "取消拉黑" : "拉黑";
                                               });
                    (new Helper.MessageBoxHelper()).Show("从黑名单中删除"+(b?"成功":"失败")+"！", "", this.LayoutRoot);                                               
                });
            }
            else
            {
                Dal.User.Instance.AddBlackList(_user.Name, (b) =>
                                                               {
                     _user._IsMyBlack = b ? 1 : 0;
                     Dispatcher.BeginInvoke(() =>
                     {
                         var menuBlack = (ApplicationBarMenuItem)ApplicationBar.MenuItems[1];
                         menuBlack.Text = _user.IsMyBlack ? "取消拉黑" : "拉黑";
                     });
                    (new Helper.MessageBoxHelper()).Show("加入黑名单" + (b ? "成功" : "失败") + "！", "", this.LayoutRoot); 
                });
            }
        }

    }
}
